package com.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.SoftReference;

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2/7/21
 */
public class ActivityUtils {

    private static SoftReference<Activity> currentActivity;
    public static void init(Application application) {
        application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks());
    }

    @Nullable
    public static Activity getCurrentTopActivity() {
        if (currentActivity==null){
            return null;
        }
        return currentActivity.get();
    }

    public static class ActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks{

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {

        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            currentActivity = new SoftReference<>(activity);
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            if (currentActivity.get()!=activity){
                return;
            }
            currentActivity = null;
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {

        }
    }
}